package Controller;

import Model.User;
import Model.permission.*;
import Service.RoleService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import utils.ResponseBody.JsonResponse;
import utils.ResponseBody.ResponseStatus;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/auth")
public class  RoleController {

  private static final Logger logger = LoggerFactory.getLogger(RoleController.class);

  @Resource
  private RoleService roleService;

  /**
   * 跳转到角色列表
   * @return
   */
  @RequestMapping("/RoleMaterials")
  public ModelAndView toPage(){
    return new ModelAndView("/YiBaoMonitor/SysMonitor/RoleMaterials");
  }

  /**
   * 跳转到权限树管理
   */
  @RequestMapping(value="toPermissionTree", method = RequestMethod.GET)
  public ModelAndView toPermissionTree(){
    logger.debug("权限列表！");
    ModelAndView mav = new ModelAndView("/YiBaoMonitor/SysMonitor/permList");
    List<Permission> permissions = null;
    try {
      permissions = roleService.findPerms();
      String permList = JSON.toJSONString(permissions, SerializerFeature.DisableCircularReferenceDetect,
              SerializerFeature.WriteDateUseDateFormat);
      logger.debug(permList);
      mav.addObject("permList", permList);
      mav.addObject("msg", "ok");
    } catch (Exception e) {
      e.printStackTrace();
      mav.addObject("msg", "false");
    }
    return mav;
  }

  /**
   * 角色列表
   */
  @RequestMapping(value = "/getRoleList")
  @ResponseBody
  public JsonResponse getRoleList() {
    System.out.println("角色列表！");
    JsonResponse result = new JsonResponse(ResponseStatus.SUCCESS);
    List<Role> roleList = null;
    try {
      roleList = roleService.roleList();
      System.out.println("角色列表查询=roleList:" + roleList);
    } catch (Exception e) {
      e.printStackTrace();
      logger.error("角色查询异常！", e);
      result.set(ResponseStatus.ERROR, e.getMessage());
      return result;
    }
    System.out.println("角色列表：" + roleList);
    result.setData(roleList);
    return result;
  }

  /**
   * 根据id查询角色
   *
   * @return PermTreeDTO
   */
  @RequestMapping(value = "/updateRole/{id}", method = RequestMethod.POST)
  //@ResponseBody
  public ModelAndView updateRole(@PathVariable("id") Integer id) {
    System.out.println("查询操作的id为："+id);
    ModelAndView mv = new ModelAndView("/YiBaoMonitor/SysMonitor/RoleMaterials");
    System.out.println("查询操作的id为："+mv);
    try {
      if (null == id) {
        System.out.println("出现错误");
        mv.addObject("msg", "请求参数有误，请您稍后再试");
        return mv;
      }
      mv.addObject("flag", "updateRole");//*********
      RoleVO rvo = this.roleService.findRoleAndPerms(id);
      System.out.println("成功："+rvo);
      //角色下的权限
      List<RolePermissionKey> rpks = rvo.getRolePerms();
      //获取全部权限数据
      List<Permission> pvos = roleService.findPerms();
      System.out.println("再次成功："+pvos);
      for (RolePermissionKey rpk : rpks) {
        //设置角色下的权限checked状态为：true
        for (Permission pvo : pvos) {
          if (String.valueOf(rpk.getPermitId()).equals(String.valueOf(pvo.getId()))) {
            pvo.setChecked(true);
          }
        }
      }
      JSONArray json_pvos = JSONArray.fromObject(pvos);
      mv.addObject("perms", json_pvos);
      //角色详情
      mv.addObject("roleDetail", rvo);
      System.out.println("根据id查询角色数据："+mv);
    } catch (Exception e) {
      e.printStackTrace();
      logger.error("添加角色并授权！异常！", e);
      mv.addObject("msg", "请求异常，请您稍后再试");
    }
    System.out.println("MV:"+mv);
    return mv;
  }

  /**
   * 更新角色并授权
   *
   * @return PermTreeDTO
   */
  @RequestMapping(value = "/setRole", method = RequestMethod.POST)
  @ResponseBody
  public JsonResponse setRole(Role role, @RequestParam("rolePermIds") String permIds) {
    System.out.println("更新角色并授权！角色数据role1：" + role + "，权限数据permIds：" + permIds);
    JsonResponse result = new JsonResponse(ResponseStatus.PARAM_ERROR);
    if (StringUtils.isEmpty(permIds)) {
        result.setMsg("无效的权限");
        return result;
    }
    if (null == role) {
        result.setMsg("无效的角色信息");
        return result;
    }
    try {
      role.setUpdateTime(new Date());
      if(roleService.updateRole(role, permIds)){
          result.set(ResponseStatus.SUCCESS, "ok");
      }else{
          result.set(ResponseStatus.ERROR, "角色错误");
      }
    } catch (Exception e) {
      e.printStackTrace();
      logger.error("更新角色并授权！异常！", e);
        result.set(ResponseStatus.ERROR, e.getMessage());
    }
    return result;
  }

  /**
   * 删除角色以及它对应的权限
   * @param id
   * @return
   */
  @RequestMapping(value = "/delRole", method = RequestMethod.POST)
  @ResponseBody
  public JsonResponse delRole(@RequestParam("roleId") int id){
    logger.debug("删除角色以及它对应的权限--id--" + id);
    JsonResponse result = new JsonResponse(ResponseStatus.PARAM_ERROR);

    if (id <= 0) {
      result.setMsg("无效的角色信息");
      return result;
    }
    try{
      if(roleService.delRole(id)){
        result.set(ResponseStatus.SUCCESS, "ok");
      }else{
        result.set(ResponseStatus.ERROR, "角色错误");
      }
    } catch(Exception e){
      e.printStackTrace();
      logger.debug("删除角色异常！",e);
      result.set(ResponseStatus.ERROR, e.getMessage());
    }
    return result;
  }

  /**
   * 查询权限树数据
   * @return
   */
  @RequestMapping(value = "/getPermissionTree")
  @ResponseBody
  public JsonResponse getPermissionTree() {
    logger.debug("权限树列表！");
    JsonResponse result = new JsonResponse(ResponseStatus.SUCCESS);
    List<Permission> pvo = null;
    try {
      pvo = roleService.findPerms();
      logger.debug("权限树列表查询=pvo:" + pvo);
    } catch (Exception e) {
      e.printStackTrace();
      logger.error("权限树列表查询异常！", e);
      result.set(ResponseStatus.ERROR, e.getMessage());
      return result;
    }
    result.setData(pvo);
    return result;
  }

  /**
   * 查询角色权限Id
   * @param roleId
   * @return
   */
  @RequestMapping(value = "/selectPermissionIdOfRole")
  @ResponseBody
  public JsonResponse selectPermissionIdOfRole(@RequestParam("id") int roleId){
    logger.debug("查询角色权限, 角色id=" + roleId);
    JsonResponse result = new JsonResponse(ResponseStatus.ERROR);
    if(roleId <= 0){
      result.set(ResponseStatus.PARAM_ERROR, "无效的角色");
      return result;
    }
    List<Integer> permissionId;
    try{
        permissionId = roleService.selectPermissionIdOfRole(roleId);
    }catch(Exception e){
      e.printStackTrace();
      logger.error("获取权限异常！",e);
      result.setMsg(e.getMessage());
      return result;
    }
    result.setData(permissionId);
    result.set(ResponseStatus.SUCCESS, "ok");
    return result;
  }

  /**
   * 添加角色并授权
   * @param permIds
   * @param role
   * @return
   */
  @RequestMapping(value = "/addRole", method = RequestMethod.POST)
  @ResponseBody
  public JsonResponse addRole(@RequestParam("rolePermIds") String permIds, Role role){
    logger.debug("添加角色并授权！角色数据role：" + role + "，权限数据permIds：" + permIds);
    JsonResponse result = new JsonResponse(ResponseStatus.PARAM_ERROR);
    if (StringUtils.isEmpty(permIds)) {
      result.setMsg("无效的权限");
      return result;
    }
    if (null == role) {
      result.setMsg("无效的角色信息");
      return result;
    }
    try{
        role.setInsertTime(new Date());
        if(roleService.addRole(role,permIds)){
            result.set(ResponseStatus.SUCCESS, "ok");
        }else{
            result.set(ResponseStatus.ERROR, "角色错误");
        }
    } catch(Exception e){
      e.printStackTrace();
      logger.debug("添加角色并授权！异常！",e);
        result.set(ResponseStatus.ERROR, e.getMessage());
    }
    return result;
  }


  /**
   * 添加权限
   * @param type [0：编辑；1：新增子节点权限]
   * @param permission
   * @return
   */
  @RequestMapping(value = "/setPerm", method = RequestMethod.POST)
  @ResponseBody
  public JsonResponse setPerm(@RequestParam("type") int type, Permission permission){
    logger.debug("设置权限--区分type-" + type + "[0：编辑；1：新增子节点权限]，权限--permission-" + permission);
    JsonResponse result = new JsonResponse(ResponseStatus.PARAM_ERROR);
    try{
      if(null != permission){
        Date date = new Date();
        if(0 == type){
          permission.setUpdateTime(date);
          //编辑权限
          if(this.roleService.updatePerm(permission)){
            result.set(ResponseStatus.SUCCESS, "ok");
          }
        }else if(1 == type){
          permission.setInsertTime(date);
          //增加子节点权限
          Permission newPermission = this.roleService.addPermission(permission);
          if(newPermission != null){
            result.set(ResponseStatus.SUCCESS, "ok");
            result.setData(permission);
            logger.debug("new permission id=", newPermission.getId());
          }else{
            result.setMsg("新建失败");
          }
        }
      }
    }catch(Exception e){
      e.printStackTrace();
      logger.error("权限设置异常！",e);
      result.set(ResponseStatus.ERROR, e.getMessage());
//      result.setData(permission);
    }
    return result;
  }


  /**
   * 获取权限数结点
   * @param id
   * @return
   */
  @RequestMapping(value = "/getPermission", method = RequestMethod.GET)
  @ResponseBody
  public JsonResponse getPermission(@RequestParam("id") int id){
    logger.debug("获取权限--id--" + id);
    JsonResponse result = new JsonResponse(ResponseStatus.PARAM_ERROR);
    try{
      if(id > 0){
        Permission perm = this.roleService.getPermission(id);
        if(perm != null){
          result.set(ResponseStatus.SUCCESS, "ok");
          result.setData(perm);
          logger.debug("获取权限成功！--permission--" + perm);
        }else{
          result.setMsg("权限不存在");
        }
//        session.setAttribute(SessionObj.SELECTED_PERM_RECORD, perm);
      }
    }catch(Exception e){
      e.printStackTrace();
      logger.error("获取权限异常！",e);
      result.set(ResponseStatus.ERROR, e.getMessage());
    }
    return result;
  }

  /**
   * 删除权限数结点
   * @param id
   * @return
   */
  @RequestMapping(value = "/del", method = RequestMethod.POST)
  @ResponseBody
  public JsonResponse delPermission(@RequestParam("id") int id){
    logger.debug("删除权限--id--" + id);
    JsonResponse result = new JsonResponse(ResponseStatus.PARAM_ERROR);
    try{
      if(id > 0){
        String msg = this.roleService.delPermission(id);
        if(msg.equals("ok")){
          result.setCode(ResponseStatus.SUCCESS);
        }
        result.setMsg(msg);
      }
    }catch(Exception e){
      e.printStackTrace();
      logger.error("删除权限异常！",e);
      result.set(ResponseStatus.ERROR, e.getMessage());
    }
    return result;
  }

  /**
   * 根据用户id查询权限树数据
   *
   * @return PermTreeDTO
   */

  @RequestMapping(value = "/getUserPerms", method = RequestMethod.GET)
  @ResponseBody
  public JsonResponse getUserPerms(HttpSession session) {
    logger.debug("根据用户id查询限树列表！");

    JsonResponse result = new JsonResponse(ResponseStatus.NO_LOGIN);
    User existUser = (User) session.getAttribute("currentUser");
    if (null == existUser) {
      logger.debug("根据用户id查询限树列表！用户未登录");
      return result;
    }

    try {
        List<Permission> permissions;
        //TODO 测试员拥有所有权限
        if(existUser.getRole_id() == 0){
          permissions = roleService.findPerms();
        }else{
          permissions = roleService.getUserPerms(existUser.getUser_id());
        }
        existUser.setPermissions(permissions);
        result.set(ResponseStatus.SUCCESS, "ok");
        result.setData(permissions);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error("根据用户id查询权限树列表查询异常！", e);
        result.set(ResponseStatus.ERROR, e.getMessage());
    }

    return result;
  }

}
